/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.edu.entity.TEduTeacherinfoEntity;
import io.renren.modules.edu.service.TEduTeacherinfoService;
import io.renren.modules.edu.vo.ScientificFileVO;
import io.renren.modules.security.SecurityUser;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

	/**
	 * 上传文件资源路径
	 */
	@Value("${upload.path}")
	private String path;

	/**
	 * 上传文件资源路径
	 */
	@Value("${upload.uploads}")
	private String uploadsPath;

	@Value("${fileUrl}")
	private String fileUrl;

	private static final String FILE_SUFFIX = "jpg,png,tif,gif";

	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private TEduTeacherinfoService tEduTeacherinfoService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		Long createUserId = (Long)params.get("createUserId");

		IPage<SysUserEntity> page = this.page(
			new Query<SysUserEntity>().getPage(params),
			new QueryWrapper<SysUserEntity>()
				.like(StringUtils.isNotBlank(username),"username", username)
				.eq(createUserId != null,"create_user_id", createUserId)
		);
		// 获取所有的教师信息
		List<TEduTeacherinfoEntity> eduTeacherinfoEntityList = tEduTeacherinfoService.getBaseMapper().selectList(null);
		Map<Long, List<TEduTeacherinfoEntity>> collect = eduTeacherinfoEntityList.stream().collect(Collectors.groupingBy(e -> e.getSysUserId()));

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		page.getRecords().forEach(e -> {
			Long createDate = e.getCreateDate();
			e.setCreateTime(simpleDateFormat.format(new Date(createDate)));
			if (CollectionUtils.isNotEmpty(collect.get(e.getId()))) {
				e.setIsHaveTeacherInfo(1);
			} else {
				e.setIsHaveTeacherInfo(0);
			}
		});

		return new PageUtils(page);
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	public SysUserEntity queryByRealName(String realName) {
		QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("real_name", realName);
		return this.baseMapper.selectOne(wrapper);
	}

	@Override
    public SysUserEntity queryUser(String realName, String mobile) {
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("real_name", realName);
        wrapper.eq("mobile", mobile);
		return this.baseMapper.selectOne(wrapper);
    }

    @Override
	@Transactional
	public void saveUser(SysUserEntity user) {
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		this.save(user);

		//检查角色是否越权
		checkRole(user);

		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public void update(SysUserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		this.updateById(user);

		//检查角色是否越权
		checkRole(user);

		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(Long[] userId) {
		this.removeByIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}

    @Override
    public ScientificFileVO uploadPicture(MultipartFile uploadFile) {
		if (uploadFile == null) {
			//判断文件是否为空
			throw new RRException("请重新上传图片！");
		}
		// 获取源文件名
		String oldFileName = uploadFile.getOriginalFilename();
		// 获取后缀名
		String extension = FilenameUtils.getExtension(oldFileName);
		// 判断文件名是否合法
		if (!FILE_SUFFIX.contains(extension)) {
			throw new RRException("文件格式不符合要求！请重新上传图片！");
		}
		// 对文件重新命名
		String uuid = UUID.randomUUID().toString();
		String newFileName = uuid + "." + extension;
		ScientificFileVO scientificFileVO = new ScientificFileVO();
		try {
			// 判断文件夹是否存在，不存在则创建
			String filePath = DateUtils.format(new Date(), "yyyyMMdd");
			File targetFile = new File(this.path + this.uploadsPath + File.separator + filePath);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 将文件写到服务器指定的文件
			String pathName = this.path + this.uploadsPath + File.separator + filePath + File.separator + newFileName;
			File dest = new File(pathName);
			uploadFile.transferTo(dest);
			// 将图片名称和地址传出
			scientificFileVO.setFileName(filePath + "/" + newFileName);
			scientificFileVO.setFileAddress(this.fileUrl + this.uploadsPath + "/" + filePath + "/" + newFileName);
		} catch (IOException e) {
			throw new RRException("Upload error");
		}
		return scientificFileVO;
	}

    /**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(SecurityUser.getUser().getId() == Constant.SUPER_ADMIN){
			return ;
		}

		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreator());

		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}
}
